package com.yhyvr.console.controller;

import com.alibaba.fastjson.JSON;
import com.lz.kit.LogKit;
import com.lz.mybatis.jdbc.auto.dao.BoOrderOperLogMapper;
import com.lz.mybatis.jdbc.auto.dao.BoProxyMapper;
import com.lz.mybatis.jdbc.auto.dao.BoProxyOrderGoodsMapper;
import com.lz.mybatis.jdbc.auto.dao.BoProxyOrderMapper;
import com.lz.mybatis.jdbc.auto.model.BoProxy;
import com.lz.mybatis.jdbc.auto.model.BoProxyOrder;
import com.lz.mybatis.jdbc.auto.model.BoProxyOrderGoods;
import com.lz.mybatis.jdbc.auto.model.BoProxyOrderGoodsExample;
import com.lz.tool.BeanMapTool;
import com.lz.tool.LzStringUtils;
import com.yhyvr.console.annotation.RepeatSubmit;
import com.yhyvr.console.callback.WrightPayLogCallBack;
import com.yhyvr.console.model.common.ConsoleContext;
import com.yhyvr.constant.ProxyOrderOperConstant;
import com.yhyvr.pojo.order.OrderRefundModel;
import com.yhyvr.pojo.order.OrderShippingModel;
import com.yhyvr.pojo.req.console.BootStrapGridReq;
import com.yhyvr.pojo.resp.CommonResp;
import com.yhyvr.pojo.resp.HttpResult;
import com.yhyvr.pojo.resp.api.store.address.ApiAddressInfoResp;
import com.yhyvr.pojo.resp.console.BootStrapGridResp;
import com.yhyvr.service.ProxyOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * title:
 * </p>
 * <p>
 * description:
 * </p>
 *
 * @create 张钦
 * @update
 * @version 1.0
 * @date
 */
@Controller
public class BoProxyOrderController {
	@Resource
	private BoOrderOperLogMapper boOrderOperLogMapper;
	@Resource
	private BoProxyOrderMapper modelMapper;
	@Resource
	private ProxyOrderService proxyOrderService;
	@Resource
	private BoProxyMapper boProxyMapper;
	@Resource
	private BoProxyOrderGoodsMapper boProxyOrderGoodsMapper;
	@Resource
	private JdbcTemplate jdbcTemplate;

	@RequestMapping("/console/bo_proxy_order/list/fenxiao")
	public String list(){
		return "console/boProxyOrder/boProxyOrder_table_fenxiao";
	}

	@RequestMapping("/console/bo_proxy_order/json/fenxiao")
	public @ResponseBody
	BootStrapGridResp json(BootStrapGridReq bootGridReq,String goodsId,String payType,String startTime,String endTime){

		StringBuffer sql = new StringBuffer("select b.*,g.order_goods_title goods_name,g.order_goods_number goods_number,g.order_goods_price goods_price from bo_proxy_order_goods g LEFT JOIN bo_proxy_order b  on  g.order_id = b.order_id where 1=1 ");
		ControllerQueryTool.setBoProxyOrderCriteria(bootGridReq.getQuery(),sql,"b");
		if(StringUtils.isNotBlank(startTime)){
			sql.append(" and b.create_time >= '"+startTime+" 00:00:00"+"'");
		}
		if(StringUtils.isNotBlank(endTime)){
			sql.append(" and b.create_time <= '"+endTime+" 00:00:00"+"'");
		}
		if(StringUtils.isNotBlank(payType)){
			sql.append(" and b.order_pay_state in ("+payType+")");
		}
		if(StringUtils.isNotBlank(goodsId)){
			sql.append(" and g.goods_id = '"+goodsId+"'");
		}
		if(bootGridReq.getSort()!=null) {
			sql.append(" order by b."+LzStringUtils.chageStringUpCaseAnd_(bootGridReq.getSort()) + " " + bootGridReq.getOrder()+",b.order_id desc");
		}else{
			sql.append(" order by b.create_time desc,b.order_id desc");
		}
		Long total = jdbcTemplate.queryForObject("select COUNT(*)  from ("+sql.toString()+")s ",Long.class);
		sql.append(" limit "+bootGridReq.getOffset()+","+bootGridReq.getLimit());
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql.toString());
		List<Map<String, Object>> lists =BeanMapTool.changeListMapToTuoFeng(maps);
		for (Map<String, Object> map : lists) {
			map.put("orderOperState",String.valueOf(map.get("orderPayState"))+String.valueOf(map.get("orderDeliveryState"))+String.valueOf(map.get("orderLockState")));
			if(StringUtils.isNotBlank(String.valueOf(map.get("proxyId")))){
				BoProxy boProxy = boProxyMapper.selectByPrimaryKey(String.valueOf(map.get("proxyId")));
				map.put("proxyName",boProxy==null?"找不到该代理商":boProxy.getBoProxyNickName());
			}

		}
		return new BootStrapGridResp(total,lists);
	}

	/**
	 * 发货申请
	 * @param id
	 * @param consoleContext
	 * @return
	 */
	@RepeatSubmit(isAdd = false,tokenName = "order_token")
	@RequestMapping("/console/bo_proxy_order/fenxiao/shipments/do/{id}")
	public @ResponseBody HttpResult sipmentsDo(OrderShippingModel orderShippingModel, @PathVariable  String id,  ConsoleContext consoleContext){
		BoProxyOrder boProxyOrder = modelMapper.selectByPrimaryKey(id);
		if((boProxyOrder.getOrderLockState()==0||boProxyOrder.getOrderLockState()==4)&&boProxyOrder.getOrderDeliveryState()==0&&boProxyOrder.getOrderPayState()!=2) {
			boProxyOrder.setOrderLockState(3);
			modelMapper.updateByPrimaryKey(boProxyOrder);
			proxyOrderService.shipmentCallBack(orderShippingModel,id,new WrightPayLogCallBack(consoleContext.getUserId(),id,boOrderOperLogMapper, ProxyOrderOperConstant.SHIPPING_SUCCESS));
		}else{
			if(boProxyOrder.getOrderLockState()!=0){
				return CommonResp.getError("订单正在操作！请稍后再试！");
			}else if(boProxyOrder.getOrderDeliveryState()!=0){
				return CommonResp.getError("订单已经配送不要重复发货！");
			}else if(boProxyOrder.getOrderPayState()!=1){
				return CommonResp.getError("该订单没有支付或者已经取消！");
			}
		}
		return CommonResp.getSuccess();
	}

	/**
	 * 发货处理申请
	 * @param id
	 * @param consoleContext
	 * @return
	 */
	@RepeatSubmit(isAdd = false,tokenName = "order_token")
	@RequestMapping("/console/bo_proxy_order/fenxiao/shipments/apply/{id}")
	public @ResponseBody HttpResult shipapply(OrderShippingModel orderShippingModel, @PathVariable  String id,  ConsoleContext consoleContext){
		BoProxyOrder boProxyOrder = modelMapper.selectByPrimaryKey(id);
		if((boProxyOrder.getOrderLockState()==0)&&boProxyOrder.getOrderDeliveryState()==0&&boProxyOrder.getOrderPayState()!=2) {
			boProxyOrder.setOrderLockState(4);
			modelMapper.updateByPrimaryKey(boProxyOrder);
		}else{
			if(boProxyOrder.getOrderLockState()!=0){
				return CommonResp.getError("订单正在操作！请稍后再试！");
			}else if(boProxyOrder.getOrderDeliveryState()!=0){
				return CommonResp.getError("订单已经配送不要重复发货！");
			}else if(boProxyOrder.getOrderPayState()!=1){
				return CommonResp.getError("该订单没有支付或者已经取消！");
			}
		}
		return CommonResp.getSuccess();
	}

	/**
	 * 发货页面
	 * @param modelMap
	 * @param id
	 * @return
	 */
	@RepeatSubmit(isAdd = true,tokenName = "order_token")
	@RequestMapping("/console/bo_proxy_order/fenxiao/shipments/page/{id}")
	public String shipmentsPage(ModelMap modelMap,@PathVariable String id){
		BoProxyOrder boProxyOrder = modelMapper.selectByPrimaryKey(id);
		modelMap.put("orderInfo",boProxyOrder);
		BoProxyOrderGoodsExample boProxyOrderGoodsExample = new BoProxyOrderGoodsExample();
		boProxyOrderGoodsExample.createCriteria().andOrderIdEqualTo(id);
		List<BoProxyOrderGoods> boProxyOrderGoodses = boProxyOrderGoodsMapper.selectByExample(boProxyOrderGoodsExample);
		modelMap.put("orderGoodses",boProxyOrderGoodses);
		ApiAddressInfoResp apiAddressInfoResp = new ApiAddressInfoResp();
		apiAddressInfoResp.setAddress(boProxyOrder.getShippingDetailAddress());
		apiAddressInfoResp.setConsignee(boProxyOrder.getShippingConsignee());
		apiAddressInfoResp.setPhone(boProxyOrder.getShippingPhone());
		apiAddressInfoResp.setProvince(boProxyOrder.getShippingProvince());
		apiAddressInfoResp.setCity(boProxyOrder.getShippingCity());
		apiAddressInfoResp.setCounty(boProxyOrder.getShippingCounty());
		apiAddressInfoResp.setPostCode(boProxyOrder.getShippingPostcode());
		modelMap.put("shippingAddress", apiAddressInfoResp);
		modelMap.put("id",id);
		return "console/boProxyOrder/proxy_order_shipments_fenxiao";
	}
	/**
	 * 订单详情
	 * @param modelMap
	 * @param id
	 * @return
	 */

	@RequestMapping("/console/bo_proxy_order/info/{id}")
	public String info(ModelMap modelMap,@PathVariable String id){
		BoProxyOrder boProxyOrder = modelMapper.selectByPrimaryKey(id);
		modelMap.put("orderInfo",boProxyOrder);
		BoProxyOrderGoodsExample boProxyOrderGoodsExample = new BoProxyOrderGoodsExample();
		boProxyOrderGoodsExample.createCriteria().andOrderIdEqualTo(id);
		List<BoProxyOrderGoods> boProxyOrderGoodses = boProxyOrderGoodsMapper.selectByExample(boProxyOrderGoodsExample);
		modelMap.put("orderGoodses",boProxyOrderGoodses);
		ApiAddressInfoResp apiAddressInfoResp = new ApiAddressInfoResp();
		apiAddressInfoResp.setAddress(boProxyOrder.getShippingDetailAddress());
		apiAddressInfoResp.setConsignee(boProxyOrder.getShippingConsignee());
		apiAddressInfoResp.setPhone(boProxyOrder.getShippingPhone());
		apiAddressInfoResp.setProvince(boProxyOrder.getShippingProvince());
		apiAddressInfoResp.setCity(boProxyOrder.getShippingCity());
		apiAddressInfoResp.setCounty(boProxyOrder.getShippingCounty());
		apiAddressInfoResp.setPostCode(boProxyOrder.getShippingPostcode());
		modelMap.put("shippingAddress", apiAddressInfoResp);
		modelMap.put("id",id);
		return "console/boProxyOrder/proxy_order_info";
	}
}
